/**
 * Created by xiniu on 2017/9/29.
 */
import React, {Component, PropTypes} from 'react';
import {
    Image,
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Modal,
    Dimensions,
    TextInput,
} from 'react-native';

import Toast from "react-native-simple-toast";
import AppService from "../../service/AppService";
import RString from "../../language/RString";

export default class CommentList extends Component {
    // 初始化
    constructor(props){
        super(props);
        this.state = {
            userId:'',
            userName: '',
            commentList:[],
            commentWithImgList:[],
            modalShow:false,
            filePath:null,
            visibleInput: false,
            commentValue: null,
        };
    };

    componentWillMount() {
        let  _this=this;
        AppService.getCommentByBusinessId({businessId:_this.props.suggestId,businessType:'DOCK'}).then(data => {
            if (!!data.errors === true && !!data.errors.length > 0) {
                Toast.show(data.errors[0].message);
            } else {
                if(data.result.length>0) {
                    data.allList.map(function (ele,idx) {
                        let vm = {
                            businessType:"PROJECT",
                            businessId: ele.id
                        };
                        // 获取评论图片
                        AppService.getUploadImage(vm).then(res =>{
                            if (!!res.errors === true && !!res.errors.length > 0) {
                                Toast.show(res.errors[0].message);
                            } else {
                                ele.imageList = res.attachmentList;
                                _this.state.commentWithImgList.push(ele);
                                _this.setState({
                                    commentList:_this.state.commentWithImgList||[]
                                });
                            }
                        });
                    });
                }
            }
        });
    }

    enlargeImg(url) {
        this.setState({
            modalShow:true,
            filePath:url
        });
    }

    closeModal() {
        this.setState({
            modalShow:false
        });
    }

    onToggleVisible = () => {
        this.setState({ visibleInput: !this.state.visibleInput })
    }

    onPressPublish = () => {
        const { commentValue } = this.state;
        // TODO 增加api 然后重新请求
        this.setState({ visibleInput: false });
    }

    renderCommentImage = (v, i) =>{
        return (
            <TouchableOpacity onPress={() => this.enlargeImg(v.filePath)} key={i}>
                <Image style={styles.commentImage} source={{uri: v.filePath}}/>
            </TouchableOpacity>
        )
    };

    sortNumber = (a,b) => {
        return b.postTime - a.postTime;
    }

    renderComment = (v, i) =>{
        return (
            <View style={styles.commentDetail} key={i}>
                <View style={{ flex:2 }}>
                    <Image style={styles.commentAvatar} source={require('../img/avatar_default.png')}/>
                </View>
                <View style={{ flex:11 }}>
                    <Text style={{ marginBottom:5,color:'#797979' }}>{v.userName}</Text>
                    <Text style={{ color:'#333333' }}>{v.content}</Text>
                    {v.imageList.length > 0 && <View style={styles.commentImageWrap}>
                        {v.imageList.map((value, idx) => this.renderCommentImage(value, idx))}
                    </View>}
                    <Text style={{ marginTop:2,color:'#999999',fontSize:12 }}>{v.showTime}</Text>
                </View>
            </View>
        )
    };

    render() {
        const {
            visibleInput,
            commentValue,
        } = this.state;
        return (
            <View style={styles.commentContainer}>
                <Modal
                    animationType='slide'
                    transparent={true}
                    visible={this.state.modalShow}
                    onShow={() => {}}
                    onRequestClose={() => {}} >
                    <TouchableOpacity activeOpacity={1} style={styles.modalLayout} onPress={()=>{this.closeModal()}}>
                        <Image style={styles.modalView}  source={{uri:this.state.filePath+"?x-oss-process=image/resize,m_lfit,w_640,h_640"}} resizeMode="contain" />
                    </TouchableOpacity>
                </Modal>
                <View style={styles.commentHeader}>
                    <Text style={{color: '#000', fontSize: 14}}>{RString('comment')}</Text>
                    <TouchableOpacity onPress={this.onToggleVisible}>
                        <Text style={styles.publishBtn}>发布评论</Text>
                    </TouchableOpacity>
                </View>
                {
                    visibleInput ? (
                        <View style={styles.inputContainer}>
                            <View style={styles.inputWrap}>
                                <Image
                                    style={styles.headerImage}
                                    source={require('../img/avatar.png')}
                                />
                                <TextInput
                                    style={{
                                        flex:1,
                                        borderWidth: 1,
                                        borderColor: '#DDDDDD',
                                    }}
                                    placeholder="请输入您的评论内容..."
                                    placeholderTextColor='#A9A9A9'
                                    underlineColorAndroid='transparent'
                                    multiline={true}
                                    numberOfLines={6}
                                    textAlignVertical="top"
                                    value={commentValue}
                                    onChangeText={commentValue => this.setState({ commentValue })}
                                />
                            </View>
                            <TouchableOpacity
                                style={styles.inputFooter}
                                onPress={this.onPressPublish}
                            >
                                 <Text>发布</Text>
                            </TouchableOpacity>
                        </View>
                    ) : null
                }
                <View style={styles.commentWrap}>
                    {this.state.commentList.sort(this.sortNumber).map((v, i) => this.renderComment(v, i))}
                </View>
            </View>
        );
    };
}

const styles = StyleSheet.create({
    modalLayout:{
        width:Dimensions.get('window').width,
        height:Dimensions.get('window').height,
        backgroundColor:'rgba(0,0,0,.8)'
    },
    modalView:{
        width:Dimensions.get('window').width,
        height:Dimensions.get('window').height
    },
    commentContainer:{
        flex:1,
    },
    commentWrap:{
        flex:1,
        padding: 15,
    },
    commentHeader: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 44,
        paddingLeft: 15,
        paddingRight: 15,
        backgroundColor: '#ECECF1',
    },
    publishBtn: {
        paddingTop: 3,
        paddingBottom: 3,
        paddingLeft: 6,
        paddingRight: 6,
        borderRadius: 4,
        borderWidth: 1,
        borderColor: '#DDDDDD',
    },
    inputContainer: {
        height: 97,
        backgroundColor: '#ffffff',
        padding: 15,
    },
    inputWrap: {
        height: 44,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    headerImage: {
        width: 36,
        height: 36,
        marginRight: 10,
        backgroundColor: 'red',
    },
    inputFooter: {
        marginTop: 10,
        flexDirection: 'row-reverse',
    },
    commentDetail:{
        flexDirection:'row',
        marginBottom:20
    },
    commentAvatar:{
        width:40,
        height:40,
        marginRight:15
    },
    commentImageWrap:{
        flex:1,
        flexDirection:'row',
        flexWrap:'wrap',
        marginTop:10
    },
    commentImage:{
        width:80,
        height:80,
        marginRight:10,
        marginBottom:10
    }
});
